package com.example.dormitory_system.aspect;

import com.example.dormitory_system.enums.ResultCode;
import com.example.dormitory_system.exception.ServiceException;
import jakarta.servlet.http.HttpSession;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class UserStatusCheckAspect {

    @Before(value = "@within(com.example.dormitory_system.aspect.CheckStudentRole) && !@annotation(com.example.dormitory_system.aspect.NoCheck)")
    public void before1(JoinPoint point){
        // 获取当前请求的HttpSession
        checkRole(1);
    }

    @Before(value = "@within(com.example.dormitory_system.aspect.CheckOneSysUserRole) && !@annotation(com.example.dormitory_system.aspect.NoCheck) " +
            "|| @annotation(com.example.dormitory_system.aspect.CheckOneSysUserRole)")
    public void before2(JoinPoint point){
        // 获取当前请求的HttpSession
        checkRole(2);
    }

    @Before(value = "@within(com.example.dormitory_system.aspect.CheckTwoSysUserRole) " +
            "&& !@annotation(com.example.dormitory_system.aspect.CheckOneSysUserRole)")
    public void before3(JoinPoint point){
        // 获取当前请求的HttpSession
        checkRole(2,3);
    }

    private static void checkRole(int... roles) {
        /*ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

            HttpSession session = attributes.getRequest().getSession();
            Integer role = (Integer) session.getAttribute("role");
            if (role != null) {
                boolean isValidRole = false;
                for (int r : roles) {
                    if (role == r) {
                        isValidRole = true;
                        break;
                    }
                }
                if (!isValidRole) {
                    throw new ServiceException(ResultCode.FAILED_UNAUTHORIZED);
                }
            }else if (role == null)
                throw new ServiceException(ResultCode.FAILED_UNAUTHORIZED);*/

    }
}